package com.kx.center.util;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * Date: 2015年1月28日
 * 
 * @Author: Eric.Li
 */
public class DOMHelper {
	DocumentBuilderFactory builderFactory = DocumentBuilderFactory
			.newInstance();
	
	Document document = null;
	XPathFactory factory = null;
	XPath xpath =  null;
	
	public DOMHelper(String content) {
		document = parse(content);
		initialize();
	}
	
	public DOMHelper(File file) {
		document = parse(file);
		initialize();
	}
	
	private void initialize() {
        factory = XPathFactory.newInstance();  
        xpath = factory.newXPath();  
	}

	// Load and parse XML file into DOM
	private Document parse(File file) {
		Document document = null;
		try {
			// DOM parser instance
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			// parse an XML file into a DOM tree
			document = builder.parse(file);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return document;
	}
	
	// Load and parse XML file into DOM
	private Document parse(String content) {
		Document document = null;
		try {
			// DOM parser instance
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			// parse an XML file into a DOM tree
			InputSource is = new InputSource(new StringReader(content));
			document = builder.parse(is);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return document;
	}
	
	public NodeList select(String xpathSelector) {
		XPathExpression expr;
		NodeList nodes = null;
		try {
			expr = xpath.compile(xpathSelector);
			nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET); 
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return nodes;
	}
	
	public String selectSingle(String xpathSelector) {
		NodeList nodes = select(xpathSelector);
		Node node = null;
		
		if(nodes != null && nodes.getLength() > 0) 
			node = nodes.item(0);
		
		return node == null ? null : node.getNodeValue();
	}
}
